package com.song.parallel;


import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Author Klys
 * @Date 2023/6/20 9:16
 * @Description stream流-并行处理
 * @Version 1.0
 */
public class StreamParallel {

    public static void main(String[] args) {
        final Collection<Integer> tasks = Arrays.asList(1, 2, 3, 4, 5, 6);

// 并行执行多个任务，并 求和
        final double res = tasks
                .stream()
                .parallel()    //并行流处理
                .map(task -> task)
                .reduce(0, Integer::sum);

        System.out.println("Total points (all tasks): " + res);

        IntStream list = IntStream.range(0, 10);
        Set<Thread> threadSet = new CopyOnWriteArraySet<>();
        //开始并行执行
        list.parallel().forEach(i -> {
            Thread thread = Thread.currentThread();
            System.err.println("integer：" + i + "，" + "currentThread:" + thread.getName());
            threadSet.add(thread);
        });
        Function<Thread, String> getName = Thread::getName;
        String apply = getName.apply(new Thread("myThread"));
        System.out.println(apply);
        System.out.println("all threads：" + threadSet.stream()
                .map(Thread::getName)
                .collect(Collectors.joining(":")));
    }
}
